import {Component} from '@angular/core';
import {
  Events,
  IonicPage,
  NavController,
  NavParams,
  ViewController,
  ModalController,
  ToastController
} from 'ionic-angular';
import {
  Http,
  Headers,
  RequestOptions
} from '@angular/http';
import {
  Storage
} from '@ionic/storage'
import {
  AppConfig
} from './../../app/app.config';
import {baseCommon} from '../../common/baseCommon';
import {ChatDetailPage} from '../chat-detail/chat-detail'
import {GroupsUtil} from '../../common/CommonUtil'

/**
 * Generated class for the InformationOfOthersPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-information-of-others',
  templateUrl: 'information-of-others.html',
})
export class InformationOfOthersPage {

  othersPhone: any;
  listData: any;
  ifSuccess: boolean = false;
  sessionID: any;
  othersName: any;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public http: Http,
    public storage: Storage,
    public event: Events,
    public toastCtrl: ToastController,
    public viewCtrl: ViewController,
    public modalCtrl: ModalController) {
    console.log(navParams.data);
    this.othersPhone = navParams.data.phone;
    this.othersName = navParams.data.name;
  }

  ionViewDidEnter() {
    this.storage.get('sessionID').then(val => {
      this.sessionID = val;
      baseCommon.getInfo(this.http, this.othersPhone, val)
        .then(data => {
          this.listData = data;
          this.ifSuccess = true;
        });
    })
    AppConfig.viewCtrl = this.viewCtrl;
  }

  privateChat() {
    this.PrivateChat(AppConfig.httpLoc + '/chat/privateChat?phone=' + this.othersPhone + "&sessionID=" + this.sessionID);
  }

  dismiss() {
    this.viewCtrl.dismiss()
  }

  /**
   * 更新个人信息
   *
   * @param {any} apiUrl
   * @param {any} phone
   * @param {any} password
   * @memberof ModifyDataPage
   */
  PrivateChat(apiUrl) {
    // var loading = baseCommon.showLoading(this.loadingCtrl, "慢慢地保存中...");
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });


    this.http.get(apiUrl, options)
      .toPromise()
      .then(data => {
        console.log(data);
        if (data.json().message === '成功') {
          var group = JSON.parse(data['_body']).data;
          // console.log(group);
          GroupsUtil.tryadd(group);
          let model = this.modalCtrl.create(ChatDetailPage, {
            'groupID': group.id,
            'groupName': this.othersName
          });
          model.present();
        } else {
          baseCommon.showToast(this.toastCtrl, data.json().message);
        }
      }, err => {
        console.log(err);
      })
  }

}
